package com.atguigu.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Map;

/**
 * @Author zhaoshuo
 * @ClassName RabbitmqListener
 * @Description
 */
@Configuration
public class RabbitmqListener {

    @RabbitListener(queues = {"test1.queue"})
    public void test1Listener(Message message, String msg, Channel channel) throws IOException {
        try {
            System.out.println(msg);
            int i = 1 / 0;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            if (message.getMessageProperties().isRedelivered()) {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }

    @RabbitListener(bindings = {@QueueBinding(exchange = @Exchange(name = "test2.exchange",
            durable = "true", type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
            value = @Queue(name = "test2.queue", durable = "true"), key = "test2.#")})
    public void test2Listener(Message message, String msg, Channel channel) {
        try {
            System.out.println("接收到消息: " + msg);
            System.out.println(new String(message.getBody()));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queues = {"test3.queue"})
    public void test3Listener(Message message, Map map, Channel channel) throws IOException {
        try {
            System.out.println(map);
            int i = 1 / 0;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            if (message.getMessageProperties().isRedelivered()) {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                        false, true);
            }

        }
    }
}